<template>
  <div 
    class="comment-board" 
    id="comment-board"
    :class="{ active: isActive && !controlsHidden }"
  >
    <div class="comments-container" id="comments-container" ref="commentsContainer">
      <!-- 初始加载状态 -->
      <div v-if="loading && comments.length === 0" style="text-align: center; padding: 40px;">
        <i class="fas fa-spinner fa-spin fa-3x"></i>
        <p style="margin-top: 10px;">加载中...</p>
      </div>
      
      <!-- 无留言状态 -->
      <div v-else-if="comments.length === 0" class="comment">
        <span class="comment-author">系统:</span>
        <span>暂无留言，快来发表第一条评论吧！</span>
      </div>
      
      <!-- 留言列表 -->
      <div v-else>
        <div 
          v-for="comment in comments" 
          :key="comment.id || comment.createTime"
          :class="['comment', comment.isSystem ? 'system-message' : '', comment.isFollow ? 'follow-message' : '']"
          :style="comment.isSystem || comment.isFollow ? { animation: 'none', opacity: comment.flashOpacity } : {}"
        >
          <!-- 系统消息和关注消息 -->
          <template v-if="comment.isSystem || comment.isFollow">
            <span class="comment-author">{{ comment.userName || '系统' }}:</span>
            <span>{{ comment.messageContent }}</span>
          </template>
          
          <!-- 普通用户留言 -->
          <template v-else>
            <div class="comment-header">
              <!-- 用户头像 -->
              <img v-if="comment.avatar" class="user-avatar" :src="comment.avatar" :alt="comment.displayName" />
              
              <!-- 用户信息 -->
              <div class="user-info">
                <div style="display: inline-flex; align-items: center;">
                  <span class="comment-author" :data-user-id="comment.userId">{{ comment.displayName }}</span>
                  
                  <!-- 身份标签 -->
                  <img v-if="comment.vip === 1" class="identity-badge vip" src="/qj/vip2.png" alt="VIP" title="VIP" />
                  <img v-if="comment.talent === 1" class="identity-badge talent" src="/qj/talent2.png" alt="达人" title="达人" />
                  <img v-if="comment.pilot === 1" class="identity-badge pilot" src="/qj/pilot2.png" alt="领航员" title="领航员" />
                </div>
                
                <!-- 粉丝统计 -->
                <div v-if="comment.followersCount !== undefined" class="follower-info">
                  粉丝 {{ comment.followersCount }} · 关注 {{ comment.followingCount }}
                </div>
              </div>
              
              <!-- 关注按钮 -->
              <button 
                v-if="comment.userId && comment.followStatus !== 0"
                class="follow-btn" 
                :class="{ 'following': comment.followStatus === 1 || comment.followStatus === 3, 'mutual-follow': comment.followStatus === 3 }"
                :disabled="comment.followLoading"
                @click="handleFollow(comment.userId, comment.displayName, comment)"
              >
                {{ comment.followLoading ? '处理中...' : (comment.followStatus === 3 ? '互相关注' : (comment.followStatus === 1 ? '已关注' : '关注')) }}
              </button>
            </div>
            
            <!-- 留言内容 -->
            <div class="comment-content">{{ comment.messageContent }}</div>
            
            <!-- 时间戳 -->
            <div class="comment-time" style="font-size: 11px; color: rgba(255, 255, 255, 0.5); margin-top: 4px;">
              {{ comment.createTime ? formatDate(comment.createTime) : '刚刚' }}
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="comment-input-area">
      <input 
        type="text" 
        class="comment-input" 
        v-model="newComment" 
        placeholder="输入留言..."
        @keyup.enter="submitComment"
        :disabled="submitting"
      >
      <button 
        class="submit-btn" 
        id="submit-comment"
        @click="submitComment"
        :disabled="!newComment.trim() || submitting"
      >
        <i class="fas fa-paper-plane"></i>{{ submitting ? '提交中...' : '' }}
      </button>
    </div>
  </div>
</template>

<script>
import { ref, watch, nextTick, onMounted, onUnmounted, reactive } from 'vue'
import { commentAPI, userAPI } from '../services/api.js'

export default {
  name: 'CommentBoard',
  props: {
    pointId: {
      type: String,
      default: null
    },
    controlsHidden: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    // 状态管理
    const comments = ref([])
    const newComment = ref('')
    const loading = ref(false)
    const submitting = ref(false)
    const isActive = ref(true) // 默认显示留言板
    const commentsContainer = ref(null)
    
    // 分页状态
    const pagination = reactive({
      currentPage: 1,
      isLoading: false,
      hasMore: true,
      pageSize: 10,
      total: 0,
      isReverse: true,
      totalPages: 1
    })

    // 关注状态缓存
    const followStatusCache = ref(new Map())
    
    // 动画效果相关状态
    const animatedComments = ref(new Map())

    // 检测是否为移动设备
    const isMobileDevice = () => {
      return window.innerWidth <= 768
    }

    // 滚动到底部的安全方法 - 针对移动设备优化
    const scrollToBottomSafe = (container, delayMs = 100) => {
      if (!container) return

      // 对于移动设备，使用更长的延迟
      const actualDelay = isMobileDevice() ? 300 : delayMs

      // 先尝试立即滚动
      container.scrollTop = container.scrollHeight

      // 然后在延迟后再次滚动，确保DOM完全更新
      setTimeout(() => {
        if (container) {
          const newScrollHeight = container.scrollHeight
          const currentScrollTop = container.scrollTop

          // 只有当内容高度变化或者没有滚动到底部时才再次滚动
          if (newScrollHeight !== container.scrollHeight ||
              currentScrollTop < newScrollHeight - container.clientHeight) {
            container.scrollTop = newScrollHeight
          }
        }
      }, actualDelay)
    }

    // 格式化日期
    const formatDate = (timestamp) => {
      return new Date(timestamp).toLocaleString()
    }

    // 处理关注/取消关注
    const handleFollow = async (userId, userName, comment) => {
      try {
        // 获取当前关注状态
        const followStatus = comment.followStatus !== undefined ? comment.followStatus : 
                            (followStatusCache.value.has(userId) ? followStatusCache.value.get(userId) : 2)
        
        // 如果是自己（followStatus为0），不执行任何操作
        if (followStatus === 0) {
          return
        }
        
        // 设置加载状态
        comment.followLoading = true
        
        const newStatus = followStatus === 1 || followStatus === 3 ? 2 : 1 // 1: 关注, 2: 取消关注

        // 调用API
        const response = await userAPI.followOrUnfollow(userId, newStatus)

        if (response.code === 200) {
          // 更新缓存
          followStatusCache.value.set(userId, newStatus)
          
          // 更新当前评论的关注状态
          comment.followStatus = newStatus
        } else {
          throw new Error(response.msg || '操作失败')
        }
      } catch (error) {
        console.error('关注/取消关注失败:', error)
        alert('操作失败，请重试')
      } finally {
        // 清除加载状态
        comment.followLoading = false
      }
    }

    // 添加闪烁动画效果
    const addFlashAnimation = (commentId) => {
      if (!animatedComments.value.has(commentId)) {
        const animationState = {
          opacity: 0.6,
          increasing: true,
          intervalId: null
        }
        
        animatedComments.value.set(commentId, animationState)
        
        // 查找评论对象
        const comment = comments.value.find(c => c.id === commentId)
        if (comment) {
          comment.flashOpacity = '0.6'
        }
        
        // 设置闪烁动画
        animationState.intervalId = setInterval(() => {
          if (animationState.increasing) {
            animationState.opacity += 0.1
            if (animationState.opacity >= 1) animationState.increasing = false
          } else {
            animationState.opacity -= 0.1
            if (animationState.opacity <= 0.6) animationState.increasing = true
          }
          
          // 更新评论的透明度
          const targetComment = comments.value.find(c => c.id === commentId)
          if (targetComment) {
            targetComment.flashOpacity = animationState.opacity.toString()
          }
        }, 300)
        
        // 5秒后停止闪烁
        setTimeout(() => {
          if (animationState.intervalId) {
            clearInterval(animationState.intervalId)
          }
          
          const targetComment = comments.value.find(c => c.id === commentId)
          if (targetComment) {
            targetComment.flashOpacity = '1'
          }
          
          animatedComments.value.delete(commentId)
        }, 5000)
      }
    }

    // 加载留言数据
    const loadComments = async (reset = false) => {
      if (!props.pointId) {
        console.log('未设置VR点ID，无法加载留言')
        return
      }

      if (pagination.isLoading || (!reset && !pagination.hasMore)) {
        console.log('Load comments skipped:', { pagination })
        return
      }

      pagination.isLoading = true
      loading.value = reset

      try {
        const targetPage = reset ? 1 : pagination.currentPage
        console.log('Loading comments for page:', targetPage, 'reset:', reset)

        // 对于历史加载，记录当前滚动状态，以便加载后调整
        let scrollHeightBefore = 0
        let scrollTopBefore = 0
        if (!reset && commentsContainer.value) {
          scrollHeightBefore = commentsContainer.value.scrollHeight
          scrollTopBefore = commentsContainer.value.scrollTop
          console.log('Scroll state before loading history:', { scrollHeightBefore, scrollTopBefore })
        }

        const response = await commentAPI.getComments(
          props.pointId,
          targetPage,
          pagination.pageSize
        )

        console.log('留言API返回数据:', response)
        // 处理返回的数据，兼容不同的返回格式
        let newComments = []
        let totalCount = 0
        
        if (response && response.code === 200) {
          // 格式1: {code: 200, data: {rows: [], total: 0}}
          if (response.data && response.data.rows) {
            newComments = response.data.rows
            totalCount = response.data.total || 0
          }
          // 格式2: {code: 200, rows: [], total: 0}
          else if (response.rows) {
            newComments = response.rows
            totalCount = response.total || 0
          }
        } else if (response && response.rows) {
          // 格式3: {rows: [], total: 0}
          newComments = response.rows
          totalCount = response.total || 0
        }

        // 如果是重置加载，更新总条数
        if (reset) {
          pagination.total = totalCount
          pagination.totalPages = Math.max(1, Math.ceil(totalCount / pagination.pageSize))
          comments.value = []
        }

        // 处理空数据情况
        if (newComments.length === 0) {
          if (reset) {
            // 显示无留言提示
          }
          pagination.hasMore = false
          return
        }

        // 处理每条评论数据
        const processedComments = newComments.map(comment => {
          // 检查是否为匿名用户
          const isAnonymous = comment.isAnonymous === 1
          const displayName = isAnonymous ? '匿名用户' : (comment.userName || '匿名用户')
          const userId = isAnonymous ? null : comment.userId
          
          // 从缓存中获取关注状态，如果没有则使用评论中的状态或默认值
          let followStatus = 2 // 默认未关注
          if (userId) {
            if (comment.followStatus !== undefined) {
              followStatus = comment.followStatus
              followStatusCache.value.set(userId, followStatus)
            } else if (followStatusCache.value.has(userId)) {
              followStatus = followStatusCache.value.get(userId)
            }
          }
          
          return {
            ...comment,
            displayName,
            userId,
            followStatus,
            followLoading: false,
            flashOpacity: '1'
          }
        })

        // 添加处理后的评论到列表
        if (pagination.isReverse) {
          // 反向分页模式，新数据添加到前面
          comments.value = [...processedComments, ...comments.value]
        } else {
          // 正向分页模式，新数据添加到后面
          comments.value = [...comments.value, ...processedComments]
        }

        // 更新分页状态
        pagination.hasMore = newComments.length >= pagination.pageSize
        
        // 只有在成功获取数据时才增加页码
        if (newComments.length > 0) {
          pagination.currentPage = targetPage + 1
        }

        // 对于历史加载，调整滚动位置以保持用户浏览位置不变
        if (!reset && commentsContainer.value) {
          nextTick(() => {
            const scrollHeightAfter = commentsContainer.value.scrollHeight
            const newScrollTop = scrollHeightAfter - (scrollHeightBefore - scrollTopBefore)
            commentsContainer.value.scrollTop = newScrollTop
          })
        }

        // 仅在初始加载时滚动到底部
        if (reset) {
          nextTick(() => {
            scrollToBottomSafe(commentsContainer.value)
          })
        }
      } catch (error) {
        console.error('加载留言失败:', error)
        // 添加错误提示消息
        if (reset) {
          comments.value = [{ 
            id: 'error_' + Date.now(), 
            userName: '系统', 
            messageContent: '加载留言失败，请稍后再试',
            isSystem: true,
            flashOpacity: '0.6'
          }]
          addFlashAnimation('error_' + Date.now())
        } else {
          // 添加到列表开头
          const errorComment = { 
            id: 'error_' + Date.now(), 
            userName: '系统', 
            messageContent: '加载历史留言失败，请重试',
            isSystem: true,
            flashOpacity: '0.6'
          }
          comments.value.unshift(errorComment)
          addFlashAnimation(errorComment.id)
        }
      } finally {
        pagination.isLoading = false
        loading.value = false
      }
    }

    // 提交留言
    const submitComment = async () => {
      if (!newComment.value.trim() || !props.pointId || submitting.value) {
        return
      }

      submitting.value = true

      try {
        const response = await commentAPI.submitComment(
          props.pointId,
          newComment.value.trim()
        )

        console.log('提交留言返回:', response)
        // 提交成功后，重置输入框并重新加载留言
        if (response && (response.code === 200 || response.success)) {
          newComment.value = ''
          // 重新加载最新留言
          await loadComments(true)
        } else {
          console.error('提交留言失败:', response)
          alert('提交留言失败，请重试')
        }
      } catch (error) {
        console.error('提交留言失败:', error)
        alert('提交留言失败，请检查网络连接')
      } finally {
        submitting.value = false
      }
    }

    // 切换留言板显示/隐藏
    const toggleCommentBoard = () => {
      if (props.controlsHidden) {
        console.log('控制栏已隐藏，无法独立控制留言板显示')
        return
      }

      isActive.value = !isActive.value
      
      if (isActive.value && props.pointId) {
        // 重置页码并加载数据
        loadComments(true)
      }
    }

    // 滚动监听函数 - 向上滚动加载历史
    let isThrottled = false
    let lastScrollTop = 0

    const handleScroll = () => {
      if (!commentsContainer.value) return

      const container = commentsContainer.value
      const scrollTop = container.scrollTop

      // 保存当前滚动位置用于下次比较
      lastScrollTop = scrollTop

      if (isThrottled || pagination.isLoading || !pagination.hasMore) {
        return
      }

      isThrottled = true
      setTimeout(() => {
        isThrottled = false
        
        // 在延迟回调中重新获取最新的滚动位置
        if (commentsContainer.value) {
          const currentScrollTop = commentsContainer.value.scrollTop
          
          // 检查是否滚动到顶部（距离顶部10px时触发）
          const isNearTop = currentScrollTop <= 10
          
          if (isNearTop) {
            console.log('滚动到顶部，触发加载历史数据')
            loadComments(false)
          }
        }
      }, 200)
    }

    // 初始化滚动分页
    const initScrollPagination = () => {
      if (commentsContainer.value) {
        // 先移除旧的监听器
        commentsContainer.value.removeEventListener('scroll', handleScroll)
        // 添加新的监听器
        commentsContainer.value.addEventListener('scroll', handleScroll)
        // 初始化lastScrollTop
        lastScrollTop = commentsContainer.value.scrollTop
      }
    }

    // 监听VR点变化
    watch(() => props.pointId, (newPointId) => {
      if (newPointId && isActive.value) {
        // 当VR点变化时，重新加载留言
        loadComments(true)
      }
    })

    // 监听控制栏状态变化
    watch(() => props.controlsHidden, (hidden) => {
      if (hidden) {
        // 控制栏隐藏时，不显示留言板
        isActive.value = false
      }
    })

    // 初始化时加载留言
    onMounted(() => {
      console.log('CommentBoard组件挂载，当前pointId:', props.pointId)
      
      // 初始化滚动分页
      nextTick(() => {
        initScrollPagination()
      })
      
      if (props.pointId) {
        loadComments(true)
      } else {
        console.log('初始pointId为null，等待VR点变化后加载留言')
        // 添加模拟数据，以便在开发环境下更好地展示组件效果
        comments.value = [
          {
            id: 'mock1', 
            userName: '游客1', 
            messageContent: '这是一个测试留言！',
            displayName: '游客1',
            followStatus: 2
          },
          {
            id: 'mock2', 
            userName: '游客2', 
            messageContent: '风景真不错！',
            displayName: '游客2',
            followStatus: 2
          }
        ]
      }
      
      // 挂载到全局，以便在需要时通过window访问
      window.toggleCommentBoard = toggleCommentBoard
      window.loadComments = loadComments
    })

    // 清理
    onUnmounted(() => {
      // 清除所有动画计时器
      animatedComments.value.forEach(animationState => {
        if (animationState.intervalId) {
          clearInterval(animationState.intervalId)
        }
      })
      
      // 移除滚动事件监听
      if (commentsContainer.value) {
        commentsContainer.value.removeEventListener('scroll', handleScroll)
      }
    })

    return {
      comments,
      newComment,
      loading,
      submitting,
      isActive,
      commentsContainer,
      pagination,
      toggleCommentBoard,
      loadComments,
      submitComment,
      handleFollow,
      formatDate
    }
  }
}
</script>

<style scoped>
/* 留言板容器样式 - 透明背景，仅内容区域有背景 */
.comment-board {
  position: fixed;
  bottom: 10px;
  left: 10px;
  transform: none;
  width: 350px;
  max-height: 50vh;
  z-index: 999;
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  background: transparent;
}

/* 响应式设计 - 手机上更小 */
@media (max-width: 768px) {
  .comment-board {
    width: 90%;
    max-width: 300px;
    bottom: 5px;
    max-height: 40vh;
  }
}

/* 留言容器样式 - 透明背景，内容区域有背景 */
.comments-container {
  background: transparent;
  max-height: 40vh;
  overflow-y: auto;
  padding: 0;
  scrollbar-width: none; /* 隐藏Firefox滚动条 */
  -ms-overflow-style: none; /* 隐藏IE和Edge滚动条 */
}

/* 响应式 - 手机上的留言容器高度 */
@media (max-width: 768px) {
  .comments-container {
    max-height: 30vh;
  }
}

/* 完全隐藏Webkit滚动条 */
.comments-container::-webkit-scrollbar {
  display: none;
}

/* 身份标签样式 - 图片版 */
.identity-badge {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-left: 4px;
  vertical-align: middle;
  object-fit: contain;
}

/* 评论头部布局 - 确保头像、昵称和关注按钮在一行显示 */
.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

/* 用户信息样式 */
.user-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
  background-color: #333;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

/* 用户昵称显示 - 实现过长时显示省略号 */
.comment-author {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

.follower-info {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 2px;
}

.follow-btn {
  padding: 4px 12px;
  font-size: 12px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  transition: background-color 0.3s;
}

.follow-btn:hover:not(:disabled) {
  background-color: rgba(255, 255, 255, 0.3);
}

.follow-btn.following {
  background-color: rgba(255, 95, 87, 0.3);
}

.follow-btn.mutual-follow {
  background-color: rgba(255, 179, 73, 0.3);
}

.follow-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 留言项样式 - 仅内容区域有背景 */
.comment {
  margin-bottom: 6px;
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(8px);
  padding: 12px;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  color: white;
}

.comment:hover {
  background-color: rgba(0, 0, 0, 0.5);
  border-color: rgba(255, 255, 255, 0.2);
  transform: translateX(2px);
}

.comment-content {
  padding-left: 36px;
  word-wrap: break-word;
  line-height: 1.4;
  color: rgba(255, 255, 255, 0.9);
}

/* 系统消息和关注消息样式 */
.system-message, .follow-message {
  background-color: rgba(76, 217, 100, 0.15);
  border-left: 3px solid #4CD964;
  padding: 8px 12px;
  margin: 8px 0;
  border-radius: 0 8px 8px 0;
  backdrop-filter: blur(8px);
}

.follow-message {
  border-left-color: #FF9500;
  background-color: rgba(255, 149, 0, 0.15);
}

/* 输入区域样式 - 与留言信息相同背景 */
.comment-input-area {
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(8px);
  padding: 10px;
  border-radius: 0 0 8px 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  gap: 8px;
}

.comment-input {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 8px 12px;
  color: white;
  font-size: 14px;
  outline: none;
  transition: all 0.3s ease;
}

.comment-input:focus {
  border-color: rgba(255, 255, 255, 0.4);
  background-color: rgba(255, 255, 255, 0.15);
}

.comment-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.submit-btn {
  background-color: rgba(76, 217, 100, 0.7);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.submit-btn:hover:not(:disabled) {
  background-color: rgba(76, 217, 100, 0.9);
  transform: translateY(-1px);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

/* 加载状态样式 */
.loading {
  text-align: center;
  padding: 20px;
  color: rgba(255, 255, 255, 0.7);
}

.comment-author {
  font-weight: 600;
  color: white;
  margin-right: 6px;
}

.comment-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 4px;
  display: block;
}

/* 留言板激活状态 */
.comment-board.active {
  opacity: 1;
  visibility: visible;
}

.comment-board:not(.active) {
  opacity: 0;
  visibility: hidden;
}
</style>